<?php
date_default_timezone_set('Asia/Taipei');

function baseUrl() {
	$config = $GLOBALS['CONFIG']['App'];
	extract($config);
	$file = '/' . basename($baseUrl);
	$base = dirname($baseUrl);
	if ($base === DS || $base === '.') {
		$base = '';
	}
	$GLOBALS['ENV']['webroot'] = $base .'/';
	return $base . $file;
}

function dispatch_uri() {
	foreach (array('HTTP_X_REWRITE_URL', 'REQUEST_URI', 'argv') as $var) {
		if ($uri = env($var)) {
			if ($var == 'argv') {
				$uri = $uri[0];
			}
			break;
		}
	}
	$base = preg_replace('/^\//', '', '' . $GLOBALS['CONFIG']['App']['baseUrl']);

	if ($base) {
		$uri = preg_replace('/^(?:\/)?(?:' . preg_quote($base, '/') . ')?(?:url=)?/', '', $uri);
	}
	if (PHP_SAPI == 'isapi') {
		$uri = preg_replace('/^(?:\/)?(?:\/)?(?:\?)?(?:url=)?/', '', $uri);
	}
	if (!empty($uri)) {
		if (key($_GET) && strpos(key($_GET), '?') !== false) {
			unset($_GET[key($_GET)]);
		}
		$uri = preg_split('/\?/', $uri, 2);

		if (isset($uri[1])) {
			parse_str($uri[1], $_GET);
		}
		$uri = $uri[0];
	} else {
		$uri = env('QUERY_STRING');
	}
	if (is_string($uri) && strpos($uri, 'index.php') !== false) {
		list(, $uri) = explode('index.php', $uri, 2);
	}
	if (empty($uri) || $uri == '/' || $uri == '//') {
		return '';
	}
	return str_replace('//', '/', '/' . $uri);
}

function dispatch_getUrl($uri = null, $base = null) {
	if (empty($_GET['url'])) {
		if ($uri == null) {
			$uri = dispatch_uri();
		}
		if ($base == null) {
			$base = $GLOBALS['ENV']['base'];
		}
		$url = null;
		$tmpUri = preg_replace('/^(?:\?)?(?:\/)?/', '', $uri);
		$baseDir = preg_replace('/^\//', '', dirname($base)) . '/';

		if ($tmpUri === '/' || $tmpUri == $baseDir || $tmpUri == $base) {
			$url = $_GET['url'] = '/';
		} else {
			if ($base && strpos($uri, $base) !== false) {
				$elements = explode($base, $uri);
			} elseif (preg_match('/^[\/\?\/|\/\?|\?\/]/', $uri)) {
				$elements = array(1 => preg_replace('/^[\/\?\/|\/\?|\?\/]/', '', $uri));
			} else {
				$elements = array();
			}

			if (!empty($elements[1])) {
				$_GET['url'] = $elements[1];
				$url = $elements[1];
			} else {
				$url = $_GET['url'] = '/';
			}

			if (strpos($url, '/') === 0 && $url != '/') {
				$url = $_GET['url'] = substr($url, 1);
			}
		}
	} else {
		$url = $_GET['url'];
	}
	if ($url{0} == '/') {
		$url = substr($url, 1);
	}
	return $url;
}

function dispatch() {
	$GLOBALS['ENV']['base'] = baseUrl();
	$url = dispatch_getUrl();
	if(empty($url)){
		$GLOBALS['ENV']['params']['controller']='launcher';
		$GLOBALS['ENV']['params']['action']='index';
	}else{
		$url_param=split('/',$url);
		if($url_param[0]=='admin'){
			$GLOBALS['ENV']['params']['admin']=true;
			unset($url_param[0]);
			$url_param=array_values($url_param);
		}else{
			$GLOBALS['ENV']['params']['admin']=false;
		}
		$GLOBALS['ENV']['params']['controller']=$url_param[0];
		unset($url_param[0]);
		$url_param=array_values($url_param);
		if(empty($url_param)||empty($url_param[0])){
			$GLOBALS['ENV']['params']['action']='index';
			$GLOBALS['ENV']['params']['data']=array();
		}else{
			$GLOBALS['ENV']['params']['action']=$url_param[0];
			unset($url_param[0]);
			$url_param=array_values($url_param);
			if(is_array($url_param)){
				$GLOBALS['ENV']['params']['data']=$url_param;
			}else{
				$GLOBALS['ENV']['params']['data']=array();
			}
		}
	}
	$ctrl_file='./app/controllers/'.$GLOBALS['ENV']['params']['controller'].'_controller.php';
	if(file_exists($ctrl_file)){
		include($ctrl_file);
	}else{
		throw new Exception('無法載入Controller: '.$GLOBALS['ENV']['params']['controller']);
	}
	$class_name=$GLOBALS['ENV']['params']['controller'].'Controller';
	$controller= new $class_name();
	$methods = array_flip($controller->methods);
	if (!isset($methods[strtolower($GLOBALS['ENV']['params']['action'])])) {
		//TODO: Scaffold feature
		/*
		if ($controller->scaffold !== false) {
		App::import('Controller', 'Scaffold', false);
		return new Scaffold($controller, $params);
		}
		*/
		throw new Exception('無法載入Action: '.$GLOBALS['ENV']['params']['action']);
	}
	$controller->constructClasses();
	$controller->Component=new Component();
	$controller->Component->initialize($controller);
	$controller->beforeFilter();
	$controller->Component->startup($controller);
	if(count($GLOBALS['ENV']['params']['data'])>0){
		call_user_func_array(array($controller,$GLOBALS['ENV']['params']['action']),$GLOBALS['ENV']['params']['data']);
	}else{
		call_user_func_array(array($controller,$GLOBALS['ENV']['params']['action']),array());
	}
	if($controller->output==null){
		$controller->render();
		echo($controller->output);
	}else{
		echo($controller->output);
	}
	return;
}
